//
//  PywBuriedManager.m
//  PywSdk
//
//  Created by Ampaw on 2017/11/15.
//  Copyright © 2017年 Jade. All rights reserved.
//

#import "PywBuriedManager.h"
#import "PywBuriedRequestService.h"
#import "PywBuriedDataHandler.h"
#import "PywAppInfo.h"
#import "PywPlatformMain.h"
#import <objc/runtime.h>

@implementation PywBuriedManager
static PywBuriedManager *manager;
+ (PywBuriedManager *)manager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[PywBuriedManager alloc] init];
    });
    return manager;
}

/**
 存储用户行为数据
 
 @param page_sn     页面编号
 @param action_sn   行为编号
 @param type_sn     类型编号
 */
- (void)saveUserActionDataWithPageSn:(NSString *)page_sn
                            actionSn:(NSString *)action_sn
                              typeSn:(NSString *)type_sn
{
    // 渠道id
    NSString *channel_id = [PywAppInfo sharedAppInfo].appType == AppTypePYW ? @"21":@"23";
    // 操作系统
    NSString *os = @"IOS";
    
    PywBuriedDataHandler *userActionData = [[PywBuriedDataHandler alloc] init];
    userActionData.page_sn = page_sn;
    userActionData.action_sn = action_sn;
    userActionData.type_sn = type_sn;
    userActionData.game_id = [PywAppInfo sharedAppInfo].gameId;
    userActionData.channel_id = channel_id;
    userActionData.promo_code = [PywAppInfo sharedAppInfo].promo_code;
    userActionData.promo_channel = [PywAppInfo sharedAppInfo].promo_channel;
    userActionData.action_time = [self getCurrentActionTime];
    userActionData.ip = [PywAppInfo sharedAppInfo].ip_address;
    userActionData.os = os;
    userActionData.imei = [PywAppInfo sharedAppInfo].uuid;
    userActionData.account = [PywPlatformMain sharedPlatformMain].account;
    
    NSLog(@"埋点需求，统计存储数据：%@",[self entityToDictionary:userActionData].description);
    [PywBuriedDataHandler saveUserActionDataWithUserActionData:userActionData];
}
//实体对象转为字典对象【调试代码】
- (NSDictionary *)entityToDictionary:(id)entity
{
    Class clazz = [entity class];
    u_int count;
    
    objc_property_t* properties = class_copyPropertyList(clazz, &count);
    NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count];
    NSMutableArray* valueArray = [NSMutableArray arrayWithCapacity:count];
    
    for (int i = 0; i < count ; i++)
    {
        objc_property_t prop=properties[i];
        const char* propertyName = property_getName(prop);
        
        [propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
        
        //        const char* attributeName = property_getAttributes(prop);
        //        NSLog(@"%@",[NSString stringWithUTF8String:propertyName]);
        //        NSLog(@"%@",[NSString stringWithUTF8String:attributeName]);
        
        id value =  [entity performSelector:NSSelectorFromString([NSString stringWithUTF8String:propertyName])];
        if(value ==nil)
            [valueArray addObject:[NSNull null]];
        else {
            [valueArray addObject:value];
        }
        //        NSLog(@"%@",value);
    }
    
    free(properties);
    
    NSDictionary* returnDic = [NSDictionary dictionaryWithObjects:valueArray forKeys:propertyArray];
//    NSLog(@"%@", returnDic);
    
    return returnDic;
}
/// 获取当前行为时间
- (NSString *)getCurrentActionTime
{
    // 获取当前系统事件并设置格式
    NSDate *date = [NSDate date]; // 获得时间对象
    NSDateFormatter *forMatter = [[NSDateFormatter alloc] init];
    [forMatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateStr = [forMatter stringFromDate:date];
//    NSLog(@"当前时间：%@",dateStr);
    return dateStr;
}

/**
 上传用户行为数据
 
 */
- (void)uploadUserActionData
{
    // 异步执行，上传数据的耗时操作
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_async(group, queue, ^{
        
        [[PywBuriedRequestService sharedBuriedService] requestUserActionWithParamterLists:[PywBuriedDataHandler userActionDataLists] Success:^(NSDictionary *dict) {
            NSLog(@"上传用户行为请求成功，返回数据: \nDict = %@",dict.description);
            int code = [[dict objectForKey:@"ack"] intValue];
            if (code == 200) {
                
                // 删除上报成功的用户行为数据
                [PywBuriedDataHandler removeUserActionData];
            }
            
        } Failure:^(NSError *error) {
            NSLog(@"上传用户行为数据失败！ \nError : %@",error);
        }];
    });
}

@end
